package com.wechat.app.ui.screens.chat

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.wechat.app.models.Message
import com.wechat.app.models.MessageType
import com.wechat.app.models.MockMessages
import com.wechat.app.ui.components.InitialsAvatar
import com.wechat.app.ui.navigation.navigateBack
import com.wechat.app.ui.theme.MessageBubbleGreen
import kotlinx.coroutines.launch
import java.util.Date

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatDetailScreen(chatName: String, chatAvatar: String?) {
    val contactName = chatName // Store contact name for avatar
    val messages = remember { mutableStateListOf<Message>().apply { addAll(MockMessages.getMessages()) } }
    var inputText by remember { mutableStateOf("") }
    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()
    
    LaunchedEffect(messages.size) {
        scope.launch {
            listState.animateScrollToItem(messages.size - 1)
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(chatName) },
                navigationIcon = {
                    IconButton(onClick = { navigateBack() }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(onClick = { /* TODO: More */ }) {
                        Icon(Icons.Default.MoreVert, contentDescription = "更多")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.background
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // Messages list
            LazyColumn(
                state = listState,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.background),
                contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(messages) { message ->
                    MessageBubble(
                        message = message,
                        contactName = if (message.isMe) null else contactName,
                        avatarUrl = if (message.isMe) null else chatAvatar
                    )
                }
            }
            
            // Input bar
            InputBar(
                text = inputText,
                onTextChange = { inputText = it },
                onSend = {
                    if (inputText.isNotBlank()) {
                        messages.add(
                            Message(
                                content = inputText,
                                type = MessageType.TEXT,
                                isMe = true,
                                timestamp = Date()
                            )
                        )
                        inputText = ""
                    }
                }
            )
        }
    }
}

@Composable
fun MessageBubble(
    message: Message,
    contactName: String? = null,
    avatarUrl: String? = null
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = if (message.isMe) Arrangement.End else Arrangement.Start
    ) {
        if (!message.isMe) {
            // Avatar
            if (avatarUrl != null && avatarUrl.isNotEmpty()) {
                // TODO: Load image from URL if needed
                InitialsAvatar(name = contactName ?: "User", size = 40.dp)
            } else {
                InitialsAvatar(name = contactName ?: "User", size = 40.dp)
            }
            Spacer(modifier = Modifier.width(8.dp))
        }
        
        // Message bubble
        Surface(
            color = if (message.isMe) MessageBubbleGreen else MaterialTheme.colorScheme.surface,
            shape = RoundedCornerShape(4.dp),
            modifier = Modifier.padding(horizontal = 4.dp)
        ) {
            Text(
                text = message.content,
                style = MaterialTheme.typography.bodyLarge,
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
                color = if (message.isMe) Color.Black else MaterialTheme.colorScheme.onSurface
            )
        }
        
        if (message.isMe) {
            Spacer(modifier = Modifier.width(8.dp))
            // Avatar
            InitialsAvatar(name = "我", size = 40.dp)
        }
    }
}

@Composable
fun InputBar(
    text: String,
    onTextChange: (String) -> Unit,
    onSend: () -> Unit
) {
    Surface(
        color = MaterialTheme.colorScheme.surfaceVariant,
        modifier = Modifier.fillMaxWidth()
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = { /* TODO: Mic */ }) {
                Icon(Icons.Default.Mic, contentDescription = "语音")
            }
            
            OutlinedTextField(
                value = text,
                onValueChange = onTextChange,
                modifier = Modifier
                    .weight(1f)
                    .heightIn(min = 36.dp),
                placeholder = { Text("输入消息") },
                maxLines = 5,
                colors = OutlinedTextFieldDefaults.colors(
                    focusedContainerColor = MaterialTheme.colorScheme.surface,
                    unfocusedContainerColor = MaterialTheme.colorScheme.surface
                )
            )
            
            IconButton(onClick = { /* TODO: Emoji */ }) {
                Icon(Icons.Default.EmojiEmotions, contentDescription = "表情")
            }
            
            IconButton(onClick = onSend) {
                Icon(Icons.Default.Add, contentDescription = "发送")
            }
        }
    }
}

